package com.zzyl.common.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.zzyl.common.utils.UserThreadLocal;
import org.springframework.core.env.Environment;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author byZhao
 */
@WebFilter(urlPatterns = "/member/*")
@SuppressWarnings("all")
public class WxLoginCheckFilter implements Filter {
    // 白名单
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/member/user/login",
            "/member/roomTypes");

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      // 逻辑代码
        System.out.println("111111111");
        // 强转参数
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 获取请求路径
        String reqPath = req.getRequestURI().toString();
        boolean isWhiteUrl = this.isWhiteUrl(reqPath);
        if (isWhiteUrl) {
            chain.doFilter(req, resp);
            return;
        }
        // 从请求头中获取token
        String token = req.getHeader("authorization");
        if (ObjectUtil.isEmpty(token)) {
             resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
             return;
        }
        // 编码的方式从配置文件中读取数据
        Environment env = SpringUtil.getBean(Environment.class);
        String secretKey = env.getProperty("jwt.secretKey");
        // 基于hutool工具包解析 （签名）
        boolean isValided = JWTUtil.verify(token, secretKey.getBytes());
        if (!isValided) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        Long userId = null;
        // 解析
        try {
            JWT jwt = JWTUtil.parseToken(token);
            Object id = jwt.getPayload("userId");
            userId = Long.parseLong(String.valueOf(id));
            // 将用户的id写入ThreadLocal
        }catch (Exception e){
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        // 将用户id存入ThreadLocal
        UserThreadLocal.set(userId);
        // 放行
        chain.doFilter(req, resp);

    }

    // 白名单匹配方法
    public boolean isWhiteUrl(String url) {
        return WHITE_LIST.contains(url);
    }





}
